// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package script_cmd

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"time"

	"gitcode.com/openseaotter/so_proto_gen_go.git/watch_api"
	"github.com/spf13/cobra"
)

var runTestCmd_BeforeChange string
var runTestCmd_AfterChange string
var runTestCmd_UnChangeList []string

var runTestCmd = &cobra.Command{
	Use: "test",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [script file]")
		}
		fileName := args[0]
		_, err := os.Stat(fileName)
		if err != nil { //文件不存在
			return fmt.Errorf("script not exist")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		changeInfo := &watch_api.ChangeInfo{
			ChangeId:         "test",
			WatchId:          "test",
			TimeStamp:        time.Now().UnixMilli(),
			ChangeFromUrl:    runTestCmd_BeforeChange,
			ChangeToUrl:      runTestCmd_AfterChange,
			ChangeFromDigest: genDigest(fmt.Sprintf("from:%s", runTestCmd_BeforeChange)),
			ChangeToDigest:   genDigest(fmt.Sprintf("from:%s", runTestCmd_AfterChange)),
			UnChangeUrlList:  runTestCmd_UnChangeList,
		}
		jsonData, err := json.MarshalIndent(changeInfo, "", "  ")
		if err != nil {
			return err
		}

		//写入临时文件
		f, err := os.CreateTemp("", "sa_*.json")
		if err != nil {
			return err
		}
		defer f.Close()
		defer os.Remove(f.Name())

		_, err = f.Write(jsonData)
		if err != nil {
			return err
		}
		err = f.Sync()
		if err != nil {
			return err
		}

		//运行命令
		execCmd := exec.Command(args[0], f.Name())
		execCmd.Env = []string{
			"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
		}
		execCmd.Stdout = os.Stdout
		execCmd.Stderr = os.Stderr
		return execCmd.Run()
	},
}

func init() {
	runTestCmd.Flags().StringVar(&runTestCmd_BeforeChange, "beforeChange", "", "image url before change")
	runTestCmd.Flags().StringVar(&runTestCmd_AfterChange, "afterChange", "", "image url after change")
	runTestCmd.Flags().StringArrayVar(&runTestCmd_UnChangeList, "unChange", []string{}, "unchange image url")

	runTestCmd.MarkFlagRequired("beforeChange")
	runTestCmd.MarkFlagRequired("afterChange")
}

func genDigest(content string) string {
	h := sha256.New()
	h.Write([]byte(content))
	data := h.Sum(nil)
	return "sha256:" + strings.ToLower(hex.EncodeToString(data))
}
